package com.ruoyi.cms.websocket_stomp;

import com.ruoyi.cms.chat.entity.CmsChatHistory;
import com.ruoyi.cms.chat.service.CmsChatHistoryService;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class WebSocketController {

    private final SimpMessagingTemplate template;

    @Autowired
    public WebSocketController(SimpMessagingTemplate template) {
        this.template = template;
    }
    @Resource
    private CmsChatHistoryService cmsChatHistoryService;

    /**
     * 广播
     *
     * @param msg
     */

    @PostMapping("/pushToAll")
    public void pushToAll(@RequestBody Message msg) {
        System.out.println(msg.toString());
        template.convertAndSend("/topic/all", msg.getContent());
    }

    /**
     * 接收客户端发送的消息，并转发给指定用户
     *
     * @param msg
     */
    @MessageMapping("/app/message")
    public void forwardMessageToUser(@RequestBody Message msg) {

        // 获取目标用户的用户名
        String targetUsername = msg.getTargetUsername();
        CmsChatHistory cmsChatHistory = new CmsChatHistory();
        cmsChatHistory.setSendtime(msg.getSendtime());
        cmsChatHistory.setContent(msg.getContent());
        cmsChatHistory.setFromUsername(Integer.valueOf(msg.getFromUsername()));
        cmsChatHistory.setTargetUsername(Integer.valueOf(targetUsername));
        cmsChatHistoryService.insert(cmsChatHistory);
        // 将消息发送给目标用户
        template.convertAndSendToUser(targetUsername, "/messages", msg);
    }
}
